﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Common;
using Dto;

namespace SqlServerDAL
{
    public class GroupMemberDAL
    {
        private const string Waming = "SqlServerDAL.GroupMemberDAL";

        public bool SaveGroupMemberDto(GroupMemberDto dto)
        {
            try
            {
                string sql;
                var parameters = new List<SqlParameter>
                                     {
                                         new SqlParameter("@GmUserId", SqlDbType.Int) {Value = dto.GmUserId},
                                         new SqlParameter("@GmJoinTime", SqlDbType.DateTime) {Value = dto.GmJoinTime},
                                         new SqlParameter("@GmGroupId", SqlDbType.Int) {Value = dto.GmGroupId}
                                     };

                if (dto.GmID == 0)
                {
                    sql =
                        "insert into GroupMember(GmUserId,GmJoinTime,GmGroupId) values(@GmUserId,@GmJoinTime,@GmGroupId)";
                }
                else
                {
                    sql =
                        "update GroupMember set GmUserId=@GmUserId,GmJoinTime=@GmJoinTime,GmGroupId=@GmGroupId where GmID=@GmID";
                    parameters.Add(new SqlParameter("@GmID", SqlDbType.Int) { Value = dto.GmID });
                }
                SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, sql, parameters.ToArray());
                return true;
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError(Waming + ".SaveGroupMemberDto(GroupMemberDto dto)", ex);
                return false;
            }
        }

        public int SelectCount(int userId)
        {
            try
            {
                const string sql = "select count(*) from GroupMember";
                var whereSql = "";
                var parameters = new List<SqlParameter>();
                if (userId != 0)
                {
                    whereSql += " where GmUserId=@GmUserId";
                    parameters.Add(new SqlParameter("@GmUserId", SqlDbType.Int) { Value = userId });
                }
                var red = SqlHelper.ExecuteScalar(SqlHelper.connStr, CommandType.Text, sql + whereSql,
                                                  parameters.ToArray());
                return red == DBNull.Value ? 0 : Convert.ToInt32(red);
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError(Waming + ".SelectCount(int userId)", ex);
                return -1;
            }
        }
    }
}
